package com.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.Subject;
import com.edu.entity.excel.SubjectData;
import com.edu.exceptionhandler.MyException;
import com.edu.service.SubjectService;
import org.springframework.stereotype.Component;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

	//因为SubjectExcelListener不能交给spring管理，需要自己new，不能注入其他对象，官网也说了
	//不能实现数据库操作
	public SubjectService subjectService;
	public SubjectExcelListener() {}
	public SubjectExcelListener(SubjectService subjectService) {
		this.subjectService = subjectService;
	}

	@Override
	public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
		if (subjectData == null){
			throw new MyException(20001,"文件数据为空");
		}


		//一行一行读，每次读取有两个值，第一个值一级分类，第二个值二级分类
		Subject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
		if (existOneSubject == null){
			existOneSubject = new Subject();
			existOneSubject.setParentId("0");
			existOneSubject.setTitle(subjectData.getOneSubjectName());
			subjectService.save(existOneSubject);
		}

		//获取一级分类id值
		String pid = existOneSubject.getId();

		//添加二级分类
		//判断二级分类是否重复
		Subject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
		if (existTwoSubject == null){
			existTwoSubject = new Subject();
			existTwoSubject.setParentId(pid);
			existTwoSubject.setTitle(subjectData.getTwoSubjectName());
			subjectService.save(existTwoSubject);
		}

	}

	//判断一级分类不能重复添加
	private Subject existOneSubject(SubjectService subjectService,String name){
		QueryWrapper<Subject> wrapper = new QueryWrapper<>();
		wrapper.eq("title",name);
		wrapper.eq("parent_id","0");
		Subject one = subjectService.getOne(wrapper);
		return one;
	}

	//判断二级分类不能重复添加
	private Subject existTwoSubject(SubjectService subjectService,String name,String pid){
		QueryWrapper<Subject> wrapper = new QueryWrapper<>();
		wrapper.eq("title",name);
		wrapper.eq("parent_id",pid);
		Subject two = subjectService.getOne(wrapper);
		return two;
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {

	}
}
